const FS = require('fs');


module.exports = function (grunt) {
  // 从 npm 载入任务
  grunt.loadNpmTasks("grunt-ts");
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-text-replace');
  const gameFile = 'C:/Users/胡浩然/AppData/Local/Screeps/scripts/screeps.com/';
  // 配置任务
  grunt.initConfig({
    // 清理空文件夹
    clean: {
      dist: ['dist/*', 'build/*']
    },
    // typescripts 编译任务
    'ts': {
      default: {
        options: {
          sourceMap: false,
          // 编译到的目标版本
          target: 'es5',
          rootDir: "src/"
        },
        // 要进行编译的目录及文件
        src: ["src/*.ts"],
        // 编译好的文件的输出目录
        outDir: 'build/'
      }
    },
    // 将所有源文件复制到 dist 文件夹中并展平文件夹结构
    copy: {
      // 将游戏代码推送到dist文件夹，以便在将其发送到 screeps 服务器之前可以对其进行修改。
      screeps: {
        files: [{
          expand: true,
          cwd: 'build/',
          src: '**',
          dest: 'dist/',
          filter: 'isFile',
          rename: function (dest, src) {
            return dest + src.replace(/\//g, '_');
          }
        }]
      },
      play: {
        files: [{
          src: 'dist/**',
          dest: gameFile
        }]
      },
    },
    replace: {
      //对文件内的import路径进行替换，从而修复扁平化复制打包引起的路径错误问题
      screeps: {
        src: ['dist/*.js'],
        overwrite: true,
        replacements: [{
          from: new RegExp('(?<=require\\(["|\']\\.+/)(.+)(?=["|`])', 'g'),
          to: (matchedWord) => matchedWord.replace("/", "_"),
        }, {
          from: new RegExp('(?<=require\\([\'|"])\\.\\.\\/', 'g'),
          to: (matchedWord) => matchedWord.replace("../", "./"),
        }]
      }
    },
  });
  // 将 ts 编译任务注册到默认执行命令
  grunt.registerTask('default', ['clean', 'ts', 'copy:screeps', 'replace:screeps', 'copy:play'])
}